"""
URL configuration for hmmadmin project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/5.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from django.shortcuts import redirect
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate, login as django_login
from django.contrib.auth.models import User
from health_app.views import HumanisticLoginView
import json

def home_redirect(request):
    """根路径重定向到管理后台"""
    return redirect('/admin/')

@csrf_exempt
def api_login(request):
    """全局API登录接口"""
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            username = data.get('username')
            password = data.get('password')
            
            if not username or not password:
                return JsonResponse({
                    'detail': '用户名和密码不能为空'
                }, status=400)
            
            # 认证用户
            user = authenticate(request, username=username, password=password)
            
            if user is not None:
                django_login(request, user)
                return JsonResponse({
                    'access': 'mock-jwt-access-token',  # 模拟JWT token
                    'refresh': 'mock-jwt-refresh-token',
                    'user': {
                        'id': user.id,
                        'username': user.username,
                        'email': user.email,
                        'first_name': user.first_name,
                        'last_name': user.last_name
                    }
                })
            else:
                return JsonResponse({
                    'detail': '用户名或密码错误'
                }, status=401)
                
        except json.JSONDecodeError:
            return JsonResponse({
                'detail': '无效的JSON数据'
            }, status=400)
        except Exception as e:
            return JsonResponse({
                'detail': str(e)
            }, status=500)
    
    return JsonResponse({
        'detail': '仅支持POST请求'
    }, status=405)

@csrf_exempt  
def api_register(request):
    """全局API注册接口"""
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            username = data.get('username')
            email = data.get('email')
            password = data.get('password')
            
            if not username or not password:
                return JsonResponse({
                    'detail': '用户名和密码不能为空'
                }, status=400)
                
            # 检查用户名是否已存在
            if User.objects.filter(username=username).exists():
                return JsonResponse({
                    'detail': '用户名已存在'
                }, status=400)
                
            # 检查邮箱是否已存在
            if email and User.objects.filter(email=email).exists():
                return JsonResponse({
                    'detail': '邮箱已被使用'
                }, status=400)
            
            # 创建用户
            user = User.objects.create_user(
                username=username,
                email=email,
                password=password
            )
            
            return JsonResponse({
                'message': '注册成功',
                'user': {
                    'id': user.id,
                    'username': user.username,
                    'email': user.email
                }
            })
            
        except json.JSONDecodeError:
            return JsonResponse({
                'detail': '无效的JSON数据'
            }, status=400)
        except Exception as e:
            return JsonResponse({
                'detail': str(e)
            }, status=500)
    
    return JsonResponse({
        'detail': '仅支持POST请求'
    }, status=405)

def api_logout(request):
    """全局API登出接口"""
    return JsonResponse({
        'message': '登出成功'
    })

def api_health_check(request):
    """健康检查接口"""
    return JsonResponse({
        'status': 'ok',
        'message': 'Django后端运行正常'
    })

urlpatterns = [
    path('', home_redirect, name='home'),
    path('admin/login/', HumanisticLoginView.as_view(), name='login'),
    path('admin/', admin.site.urls),
    
    # 全局API认证路由
    path('api/auth/login/', api_login, name='api_login'),
    path('api/auth/register/', api_register, name='api_register'), 
    path('api/auth/logout/', api_logout, name='api_logout'),
    
    # 健康检查接口
    path('api/health/', api_health_check, name='global_health_check'),
    
    # 包含 health_app 的 URL 配置
    path('', include('health_app.urls')),
]

# 开发环境下的静态文件和媒体文件处理
if settings.DEBUG:
    # 静态文件服务
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    # 媒体文件服务
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
